package com.liu.netty.netty;

import com.liu.netty.pojo.Message;
import com.liu.netty.service.CollectService;

import com.liu.netty.util.MessageUtil;
import io.netty.channel.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@ChannelHandler.Sharable
@Slf4j
public class ServerColletHandler  extends SimpleChannelInboundHandler<String> {

    @Autowired
    private CollectService collectService;



    @Override
    protected void messageReceived(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        System.out.println("接收到的消息为："+s);
        Message message = MessageUtil.messageDecode(s);




        String msg="";
          // 发送用户请求的时候，添加登录消息
        if(!StringUtils.isEmpty(message.getDataID())&& !StringUtils.isEmpty( message.getCommandStyle())){
            if (message.getDataID().equalsIgnoreCase("1") && message.getCommandStyle().equalsIgnoreCase("1")){
                ClientManager.addClient(message.getObjectAddress(),channelHandlerContext.channel());
            }
        }


        msg = collectService.detailMessageAndRespose(message, msg);


        System.out.println(msg);
        channelHandlerContext.writeAndFlush(msg);
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        super.handlerAdded(ctx);
        System.out.println("handlerAdded");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);

       Map<String ,Channel> clients= ClientManager.getAllClient();
       for(String key : clients.keySet()){
            if (clients.get(key).id().asLongText().equalsIgnoreCase(ctx.channel().id().asLongText())){
                log.info("日志：设备退出了连接 {}" ,key);
               clients.remove(key);
           }
       }



    }
}
